import funcs from "./wsfunc"

export class Socket {
  constructor(url, game) {
    this.game = game
    this.ws = new WebSocket(url)
    this.ws.onopen = this.onopen.bind(this)
    this.ws.onclose = this.onclose.bind(this)
    this.ws.onerror = this.onerror.bind(this)
    this.ws.onmessage = this.onmessage.bind(this)

    this.delay = 999 // 延迟
    this.funcs = funcs
  }
  updatePing(time) {
    this.delay = Math.abs(new Date().getTime() - time)
    // console.log(new Date().getTime(), time, this.delay)
    this.updatePingAfter(this.delay)
  }
  updatePingAfter() {

  }
  onopen() {
    console.log('open')
  }
  onclose() {
    console.log('close')
    this.game.Vue.notity("与服务器断开连接")
  }
  onerror() {
    console.log('error')
  }
  send(mes, func) {
    if (func) this.funcs[mes.func] = func
    mes = JSON.stringify(mes)
    this.ws.send(mes)
  }
  listen(name, func) {
    if (name) this.funcs[name] = func
  }
  onmessage(res) {
    let data = {}
    try {
      data = JSON.parse(res.data)
      this.updatePing(data.time)
      if (data.func) {
        let fname = data.func
        let kwargs = data.kwargs
        this.funcs[fname](kwargs)
      }
    } catch (error) {
      console.log('err', error)
    }
  }
}
